package ajax;

import entity.Userinfo;
import service.serviceimpl.ServiceUserImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Author wuchao66
 * @Date 2023/5/23 10:25
 * @PackageName:${PACKAGE_NAME}
 * @ClassName: ${NAME}
 * @Description: TODO
 * @Param
 * @Version 1.0
 */
@WebServlet(name = "ServletAjax",urlPatterns = "/ServletAjax")
public class ServletAjax extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();//文件流

        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();//文件流
        String name = request.getParameter("name");
        ServiceUserImpl serviceUser = new ServiceUserImpl();
        //int i = serviceUser.load("select count(1) from userinfo where name=?", name);
        List<Userinfo> list = serviceUser.executeQuery("select * from userinfo where name like ?", "%" + name + "%");
        System.out.println(list);
       // String json=[{"name":"超哥","dept":"总裁"},.........];
        //json html xml
        //做一个假的json回来
        StringBuffer sb = new StringBuffer("[");
        for(int i=0;i<list.size();i++){
            String s="{\"name\":\""+list.get(i).getName()+"\",\"dept\":\""+list.get(i).getDept()+"\"}";
            sb.append(s);
            if(i<list.size()-1){
                sb.append(",");
            }
        }
        sb.append("]");
        System.out.println(sb);
        out.print(sb);
        //        if(i>0){
//           // request.getRequestDispatcher(.) 不能这样回去-是全局刷新
//            out.print("yes");//这就回去了
//        }else{
//            out.print("n");
//        }
        out.flush();
        out.close();
    }
}
